Given an array of integers nums
and an integer k
. A continuous subarray is called nice if there are k
odd numbers on it.
Return the number of nice sub-arrays.
Input: nums = [1,1,2,1,1], k = 3 Output: 2 Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].
Input: nums = [2,4,6], k = 1 Output: 0 Explanation: There is no odd numbers in the array.
Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2 Output: 16
1 <= nums.length <= 50000
1 <= nums[i] <= 10^5
1 <= k <= nums.length
# @param {Integer[]} nums# @param {Integer} k# @return {Integer}defnumber_of_subarrays(nums,k)counter={0=>1}counter.default=0count=0ret=0nums.eachdo |x| count += 1ifx.odd?ret += counter[count - k]counter[count] += 1endretend
use std::collections::HashMap;implSolution{pubfnnumber_of_subarrays(nums:Vec<i32>,k:i32) -> i32{letmut counter = vec![(0,1)].into_iter().collect::<HashMap<_,_>>();letmut count = 0;letmut ret = 0;for i in0..nums.len(){if nums[i] % 2 == 1{ count += 1;} ret += counter.get(&(count - k)).unwrap_or(&0);*counter.entry(count).or_insert(0) += 1;} ret }}